package com.feihong.yw189.bluetooth.startreadcard;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.feihong.yw189.bluetooth.bleutils.BleHttpUtils;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.feihong.yw189.bluetooth.utils.util.BlueReaderHelper;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;

import org.codehaus.jackson.map.ObjectMapper;

import java.util.concurrent.Executors;

import cn.com.senter.helper.ConsantHelper;
import cn.com.senter.model.IdentityCardZ;
import cn.com.senter.sdkdefault.helper.Error;

/**
 * 店家联盟读卡
 * 2017/8/24
 * 张鹏
 */
public class XinTongConnectUtils {

    private String bleAddress;
    private Context context;
    private Activity mActivity;

    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    private Bitmap photo;
    private String bluetoothName = "";
    private BleHttpUtils bleHttpUtils;
    private Boolean mFlag = false;
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;
    private String bleName;
    /**
     * @param context
     * @param bleAddress
     * @param bluetoothName
     * @param flag
     * @param mOnUpLoadListener
     */
    public XinTongConnectUtils(Context context,final String bleName, String bleAddress, final String bluetoothName,
                               Boolean flag, final UpLoadListener mOnUpLoadListener) {
        this.context = context;
        this.mActivity = (Activity) context;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.mFlag = flag;
        this.bluetoothName = bluetoothName;
        this.mOnUpLoadListener = mOnUpLoadListener;
        uiHandler = new MyHandler(mActivity);
        initShareReference();
    }

    // 10002   49.117.145.10
    private String server_address = "";
    private int server_port = 0;

    private void initShareReference() {
        // 获取ip和port
        server_address = "senter-online.cn";
//        server_address = PrefUtils.getString(mActivity, ConstantsValue.XTserverIp, "49.117.145.10");
        String port = PrefUtils.getString(mActivity, ConstantsValue.XTport, "10002");
        server_port = Integer.parseInt(port);
        Log.e("项目异常", "-----initShareReference------" + server_address);
        Log.e("项目异常", "------initShareReference------" + server_port);
        //----实例化help类---
        mBlueReaderHelper = new BlueReaderHelper(mActivity, uiHandler);
        mBlueReaderHelper.setServerAddress(server_address);
        mBlueReaderHelper.setServerPort(server_port);

    }

    public void connect() {

        bleHttpUtils = new BleHttpUtils(context, bluetoothName, mFlag, new UpLoadListener() {
            @Override
            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                    String nation, String sign_office, String name, String sign_data,
                                    String birth_year, String birth_month, String birth_day,
                                    Bitmap photo, String filePhoto, String idPath, String to,
                                    String from, String born, String photoHeard) {

                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
                        photo, filePhoto, idPath, to,
                        from, born, photoHeard);
                // 读卡成功需要断开连接
                stopConnect();
            }

            @Override
            public void onErrUpLoad(String err) {
                mOnUpLoadListener.onErrUpLoad(err);
                // 读卡失败需要断开连接
                stopConnect();
            }

        });
        readCardBlueTooth();
    }

    private BlueReaderHelper mBlueReaderHelper;

    /**
     * 蓝牙读卡方式
     */
    protected void readCardBlueTooth() {

        new BlueReadTask()
                .executeOnExecutor(Executors.newCachedThreadPool());

    }

    public static Handler uiHandler;

    /**
     * 蓝牙读卡方式
     */
    private class BlueReadTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPostExecute(String strCardInfo) {
            Log.e("项目异常", "------strCardInfo------" + strCardInfo);
            if (TextUtils.isEmpty(strCardInfo)) {
//                uiHandler.sendEmptyMessage(ConsantHelper.READ_CARD_FAILED);
//                readCardFailed("2");
                return;
            }
            if (strCardInfo.length() <= 2) {
//                readCardFailed(strCardInfo);
                return;
            }
            ObjectMapper objectMapper = new ObjectMapper();
            IdentityCardZ mIdentityCardZ = new IdentityCardZ();
            try {
                mIdentityCardZ = (IdentityCardZ) objectMapper.readValue(
                        strCardInfo, IdentityCardZ.class);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(ConsantHelper.STAGE_LOG, "mIdentityCardZ failed" + e.toString());
                mOnUpLoadListener.onErrUpLoad("读卡失败0!");
                return;
            }
            readCardSuccess(mIdentityCardZ);

            super.onPostExecute(strCardInfo);
        }

        @Override
        protected String doInBackground(Void... params) {

            boolean b = mBlueReaderHelper.registerBlueCard(bleAddress);
            Log.e("项目异常", b + "------bleAddress------" + bleAddress);
            String strCardInfo = null;
            if (b) {
                strCardInfo = mBlueReaderHelper.read();
            } else {
                strCardInfo = "-1";
                mOnUpLoadListener.onErrUpLoad("请确认蓝牙设备已经连接，再读卡!");
            }
            return strCardInfo;
        }
    }

    class MyHandler extends Handler {
        private Activity activity;

        @SuppressLint("HandlerLeak")
        MyHandler(Activity activity) {
            this.activity = activity;
        }

        @Override
        public void handleMessage(final Message msg) {
            Log.e("项目异常", "------msg.what------" + msg.what);
            switch (msg.what) {
                case ConsantHelper.READ_CARD_SUCCESS:

                    break;

                case ConsantHelper.SERVER_CANNOT_CONNECT:
                    mOnUpLoadListener.onErrUpLoad("服务器连接失败! 请检查网络!");
                    break;

                case ConsantHelper.READ_CARD_FAILED:
                    mOnUpLoadListener.onErrUpLoad("无法读取信息请重试!");
                    break;

                case ConsantHelper.READ_CARD_WARNING:
                    Log.e("项目异常", "------READ_CARD_WARNING------" + msg.what);
                    String str = (String) msg.obj;
                    if(!TextUtils.isEmpty(str)){
                        if (str.indexOf("card") > -1) {
                            mOnUpLoadListener.onErrUpLoad("读卡失败: 卡片丢失,或读取错误!");
                        } else {
                            String[] datas = str.split(":");
                            mOnUpLoadListener.onErrUpLoad("网络超时 错误码: " + Integer.toHexString(new Integer(datas[1])));
                        }
                    }else{
                        mOnUpLoadListener.onErrUpLoad("读卡失败: 读取错误!");
                    }
                    break;

                case ConsantHelper.READ_CARD_PROGRESS:

                    final int progress_value = (Integer) msg.obj;
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("项目异常", "------正在读卡------" + progress_value);
                        }
                    });

//                    activity.tv_info.setText("正在读卡......");//,进度：+ progress_value + "%"
                    break;

                case ConsantHelper.READ_CARD_START:
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("项目异常", "------正在读卡2------");
                        }
                    });

//                    activity.tv_info.setText("正在读卡......");
                    break;
                case Error.ERR_CONNECT_SUCCESS:
                    String devname = (String) msg.obj;
                    Log.e("项目异常", "------连接成功------");
//                    activity.tv_info.setText(devname + "连接成功!");
                    break;
                case Error.ERR_CONNECT_FAILD:
                    final String devname1 = (String) msg.obj;
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("项目异常", "------连接失败------" + devname1);

                        }
                    });
                    mOnUpLoadListener.onErrUpLoad("连接失败!");
                    break;
                case Error.ERR_CLOSE_SUCCESS:
                    Log.e("项目异常", "------断开连接成功------");
//                    activity.tv_info.setText((String) msg.obj + "断开连接成功");
                    break;
                case Error.ERR_CLOSE_FAILD:
                    Log.e("项目异常", "------断开连接失败------");
//                    activity.tv_info.setText((String) msg.obj + "断开连接失败");
                    break;
                case Error.RC_SUCCESS:
                    final String devname12 = (String) msg.obj;
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("项目异常", "------连接成功------" + devname12);

                        }
                    });
//                    activity.tv_info.setText(devname12 + "连接成功!");
                    break;

            }
        }

    }

    /**
     * 断开连接
     */
    public void stopConnect() {
        try {
            // 断开读卡器连接
            if (mBlueReaderHelper != null) {
                boolean b = mBlueReaderHelper.unRegisterBlueCard();
                Log.e("项目异常djlm", "------断开连接------" + b);
            }

        } catch (Exception e) {
            Log.e("项目异常", "------断开连接异常------" + e.toString());
            mOnUpLoadListener.onErrUpLoad("");
            e.printStackTrace();
        }

    }

    private void readCardFailed(String strcardinfo) {
        int bret = Integer.parseInt(strcardinfo);
        switch (bret) {
            case -1:
                mOnUpLoadListener.onErrUpLoad("服务器连接失败!");
                break;
            case 1:
                mOnUpLoadListener.onErrUpLoad("读卡失败1!");
                break;
            case 2:
                mOnUpLoadListener.onErrUpLoad("读卡失败2!");
                break;
            case 3:
                mOnUpLoadListener.onErrUpLoad("网络超时!");
                break;
            case 4:
                mOnUpLoadListener.onErrUpLoad("读卡失败3!");
                break;
            case -2:
                mOnUpLoadListener.onErrUpLoad("读卡失败4!");
                break;
            case 5:
                mOnUpLoadListener.onErrUpLoad("照片解码失败!");
                break;
        }

    }

    private void readCardSuccess(IdentityCardZ identityCard) {
        if (identityCard != null) {
            address = identityCard.address.trim();
            sex = identityCard.sex.trim();
            id_num = identityCard.cardNo.trim();
            nation = identityCard.ethnicity.trim();
            sign_office = identityCard.authority.trim();
            born = identityCard.birth.trim();
            name = identityCard.name.trim();

            String[] year = born.split("年");
            String[] month = year[1].split("月");
            String[] days = month[1].split("日");
            birth_year = year[0].trim();
            birth_month = month[0].trim();
            birth_day = days[0].trim();
            born = birth_year + birth_month + birth_day;
            sign_data = identityCard.period.trim();
            from = sign_data.substring(0, 4) +
                    sign_data.substring(5, 7) +
                    sign_data.substring(8, 10);
            if (sign_data.contains("长期")) {

                to = "长期";
            } else {
                to = sign_data.substring(11, 15) +
                        sign_data.substring(16, 18) +
                        sign_data.substring(19);
            }
            photoHeard = identityCard.pictureBase64.trim();

            try {
                photo = BitmapFactory.decodeByteArray(identityCard.avatar,
                        0, identityCard.avatar.length);
                bleHttpUtils.upLoadSfzPhoto(bleName,bleAddress,address, photoHeard, sex, id_num, nation,
                        sign_office, to, name, from, born, sign_data, birth_year,
                        birth_month, birth_day, photo);

            } catch (Exception e) {
                Log.e(ConsantHelper.STAGE_LOG, "图片失败" + e.getMessage());
                mOnUpLoadListener.onErrUpLoad("图片解码失败!");
            }
        } else {
            mOnUpLoadListener.onErrUpLoad("读取数据为空!");
        }
    }
}
